import {Effect,ImmerReducer} from 'umi'
import { fetchProduct } from '@/api';
export type stateType =  {
    productList:object[] | [];
    err:string | null
}
export type productModelType = {//定义model接口
    namespace:string,
    state:stateType;
    reducers:{
        setProductList:ImmerReducer<stateType>//immerReducer用于方便的更新状态
    },
    effects:{//副作用
        getProductList:Effect
    }
}

const productModel:productModelType =  {
    namespace:'product',//命名空间
    state:{ 
        productList:[],
        err:null
    },
    reducers :{
        setProductList(state,action){
            state.productList = action.payload.data;
            state.err = action.payload.err
        }
    },
    effects:{ //副作用 相当于vuex中的actions
        *getProductList({payload},{call,put,select}):any{
            //获取数据更新reducters
            yield new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(123)
                },2000)
            })
            try{
                let res = yield call(fetchProduct)
                yield put({type:'setProductList',payload:{data:res.data,err:null}})
                
            }catch(e:any){
                yield put({type:'setProductList',payload:{data:[],err:e.toString()}})
            }
        }
    }
}

export default productModel